<?php

class Users_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    function checkUserMail($email) {
        $SQL = "SELECT COUNT(*) as usersCount 
				FROM " . USERS_TABLE . " 
				WHERE user_mail = '" . mysql_escape_string($email) . "'";
        $query = $this->db->query($SQL);
        $resultQuery = $query->row();

        if ($resultQuery->usersCount > 0)
            return true;

        return false;
    }
    
    function checkUserName($name) {
        $SQL = "SELECT COUNT(*) as usersCount 
				FROM " . USERS_TABLE . " 
				WHERE user_name = '" . mysql_escape_string($name) . "'";
        $query = $this->db->query($SQL);
        $resultQuery = $query->row();

        if ($resultQuery->usersCount > 0)
            return true;

        return false;
    }

    function validEmail($email) {
        if (preg_match("%^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$%", $email)) {
            return true;
        }
        return false;
    }

    function validLogin($login) {
        if (preg_match("/^[a-zA-Z][a-zA-Z0-9-_\.]{2,20}$/", $login)) {
            return true;
        }
        return false;
    }

    function registerUser($user_name, $user_mail, $user_pwd) {
        
        if($this->checkUserMail($user_mail))
            die("Пользователь с таким почтовым адресом уже зарегистрирован");
        if($this->checkUserName($user_name))
            die("Пользователь с таким именем уже зарегистрирован");
        
        
        $today = date("Y-m-d H:i:s");

        $SQL = "INSERT INTO " . USERS_TABLE . " (
                                        user_name,
                                        user_mail,
                                        user_pwd,
                                        user_reg_date
                                        )
                                    VALUES (
                                        '" . mysql_real_escape_string($user_name) . "',
                                        '" . mysql_real_escape_string($user_mail) . "',
                                        '" . md5($user_pwd) . "',
                                        '" . $today . "')";
        $query = $this->db->query($SQL);

        /* $this->load->library('email');
          $this->email->from('support@qrazzle.ru', 'qrazzle.ru');
          $this->email->to(mysql_escape_string($_POST['mail']));
          $this->email->subject('Регистрация на qrazzle.ru');
          $this->email->message('Поздравляем, вы зарегистрированы на сайте ihatewhen.ru под именем '.mysql_escape_string($_POST['name']).'. Для авторизации на сайте используйте этот почтовый адрес и указанный при регистрации пароль.');

          $this->email->send();/* */

        return $this->db->insert_id();
    }

    function getUser($user_id) {
        $SQL = "SELECT * FROM " . USERS_TABLE . " WHERE user_id = " . $user_id;
        $query = $this->db->query($SQL);
        return $query->row_array();
    }

    function getUserByEmail($user_email) {
        $SQL = "SELECT * FROM " . USERS_TABLE . "
                    WHERE user_mail = '" . mysql_real_escape_string($user_email) . "' LIMIT 1;";
        $query = $this->db->query($SQL);
        $result = $query->row();
        return $result;
    }

    function checkPassword($id, $pass) {
        $SQL = "SELECT * FROM " . USERS_TABLE . " WHERE user_id = " . $id;

        $query = $this->db->query($SQL);
        $result = $query->row();
        if ($result->user_pwd == md5($pass))
            return true;

        return false;
    }

    function login($email, $pass) {
        $user = $this->getUserByEmail($email);

        if (isset($user->user_id)) { //юзер с таким мылом вообще существует?
            if ($this->checkPassword($user->user_id, $pass)) { //если пароли совпадают
                $_SESSION['user_id'] = $user->user_id;

                if ($user->user_role == 1) { //если юзер является админом
                    $_SESSION['admin'] = true;
                }

                return true;
            }
        }

        return false;
    }

    function isUserExists($user_id) {
        $SQL = "SELECT * FROM " . USERS_TABLE . " WHERE user_id = " . $user_id;
        $query = $this->db->query($SQL);
        if (count($query->result_array()) > 0)
            return true;
        else
            return false;
    }

    function getUserBySocId($uid) {
        $SQL = "SELECT * FROM " . USERS_TABLE . "
				WHERE user_soc_id = " . $uid . "";
        $query = $this->db->query($SQL);
        return $query->row();
    }

    function isSocUserExist($uid) {
        $SQL = "SELECT * FROM " . USERS_TABLE . "
				WHERE user_soc_id = " . $uid . "";
        $query = $this->db->query($SQL);
        if (count($query->result_array()) > 0)
            return true;
        else
            return false;
    }

    function socUserRegister($uid, $name, $provider) {
        $today = date("Y-m-d H:i:s");

        //$avatar = $this->lib_help->getAvatar($provider);
        $avatar = "default_avatar.jpg";
        
        $SQL = "INSERT INTO " . USERS_TABLE . " 
		(
			user_name,
			user_reg_date,
			user_role,
			user_soc_id,
			user_avatar,
                        user_source
		)
		VALUES 
		(
			'" . mysql_real_escape_string($name) . "',
			'" . $today . "',
			0,
			" . $uid . ",
			'" . $avatar . "',
                        '".$provider."'
		)";
        $this->db->query($SQL);
        return $this->db->insert_id();
    }

    function checkSocUserAuth() {
        if (isset($_POST['token'])) {
            if (false === ($authData = file_get_contents('http://loginza.ru/api/authinfo?token=' . $_POST['token']))) {
                $err = 'Ошибка получения данных';
            } else {
                //include_once('thirdparty/JSON.php');
                //$json = new Services_JSON();
                $json_data = json_decode($authData);
                //print_r($json_data);
                $provider = $json_data->provider;
                $uid = $json_data->uid;
                $name = '';
                switch ($provider) {
                    case 'http://vkontakte.ru/': $name = $json_data->name->first_name . ' ' . $json_data->name->last_name;
                        break;
                    case 'http://www.facebook.com/': $name = $json_data->name->first_name . ' ' . $json_data->name->last_name;
                        break;
                    case 'http://twitter.com/': $name = $json_data->name->full_name;
                        break;
                    default: $name = "Анонимус с " . $provider;
                        break;
                }
                if ($this->isSocUserExist($uid))
                    $user_id = $this->getUserBySocId($uid)->user_id;
                else
                    $user_id = $this->socUserRegister($uid, $name, $provider);

                $_SESSION['user_id'] = $user_id;

                return true;
            }
        }

        return false;
    }
    
    function changePassword($user_mail, $old, $new)
    {
        $message = "";
        if($this->login($user_mail, $old))
        {
            $SQL = "UPDATE " . USERS_TABLE . " SET user_pwd = '". mysql_real_escape_string($new) ."' WHERE user_mail = '" . mysql_real_escape_string($user_mail) . "'";
            $query = $this->db->query($SQL);
            $message['type'] = true;
            $message['text'] = "Пароль успешно изменён!";
        }
        else
        {
            $message['type'] = false;
            $message['text'] = "Введен неправильный пароль!";
        }
        return $message;
            
    }

}
?>